# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from srm.srm.doctype.srm_server_config.srm_server_config import sync_to_k3cloud_price_adjustment_more_entrys, validate_before_price_adjustmen
from frappe.utils import now

class SRMQuotation(Document):
	def after_insert(self):
		frappe.db.set_value("SRM Inquiry Of Supplier", self.from_inquiry_of_supplier, "status", "已报价")


	def after_delete(self):
		frappe.db.set_value("SRM Inquiry Of Supplier", self.from_inquiry_of_supplier, "status", "待处理")

	@frappe.whitelist()
	def get_material_info(self, material_number):
		if frappe.db.exists({'doctype': 'SRM Source Bill Sub','material_number': material_number,'supplier': self.supplier_number}):
			material_info = frappe.get_all('SRM Material', filters = {'material_number': material_number}, fields = ['material_number', 'material_name', 'material_model', 'uom'])
			return  material_info

	# 2023-04-11: 采纳报价行
	@frappe.whitelist()
	def confirm_quotation_yes(self, row_docype, row_name):
		frappe.db.set_value(row_docype, row_name, {"selected": "采纳"})
		self.reload()

	# 2023-04-11: 不采纳报价行
	@frappe.whitelist()
	def confirm_quotation_no(self, row_docype, row_name):
		frappe.db.set_value(row_docype, row_name, {"selected": "未采纳"})
		self.reload()

	# 调用同步生成ERP调价单方法: 为确保一张报价单对应生成一张采购调价表, 所以先要拼接子表行的JSON串
	@frappe.whitelist()
	def sync_to_price_adjustment(self, session_fullname):
		# 2023-09-07: 增加对当前采购员是否已经同步了云星空的userid
		userid = frappe.get_doc('User', frappe.session.user).mobile_no
		if userid:
			# 2023-06-20: 在sync_to_k3cloud_price_adjustment前先校验, 确保供应商和采购价目表可用
			validate = validate_before_price_adjustmen(self.supplier_number)
			if validate:
				# 定义一个空的接收列表变量fbillno_r和要传参的子串pur_patentry
				fbillno_r = []
				pur_patentrys = []
				# 循环子表记录
				for i in self.material_subs:
					# 只有"采纳"的记录行才构建到JSON串去
					if i.selected == "采纳":
						pur_patentrys.append({
							"FAdjustType": "A",     # 调价类型: "A"是[新增]
							"FPriceListId": { "FNumber": self.supplier_number },       # 关联价目表: 九联是以供应商编码创建价目表,特殊规则
							"FSupplierId": { "FNumber": self.supplier_number },        # 关联供应商
							"FCurrencyId": { "FNAME": "人民币" if self.currency == "CNY" else "美元" },
							"FMaterialId": { "FNumber": i.material_number },         # 物料
							"FBeforePrice": i.last_price,
							"FAfterPrice": i.price,
							"FAfterTaxPrice": i.tax_price,
							"FAfterTaxRate": i.tax_rate,
							"FAfterPriceCoefficient": 1.0,
							"FUpPrice": i.price,
							"FDownPrice": i.price,
							"FEffectiveDate": self.price_date_from,
							"FExpiryDate": self.price_date_to
						})
				if len(pur_patentrys) > 0:
					r = sync_to_k3cloud_price_adjustment_more_entrys(docname=self.name, pur_patentry=pur_patentrys, session_fullname=session_fullname, creatorid=userid)
					if r:
						fbillno_r.append(r)
				elif len(pur_patentrys) == 0:
					frappe.msgprint('没有采纳的报价记录行!')
				# 往JS返回
				return fbillno_r
		else:
			frappe.msgprint('当前用户没有同步云星空的UserID!')